jQuery.extend(jQuery.validator.messages, {
	  required: "<img src='/images/error.jpg'>This field is required.",
	  remote:"<img src='/images/error.jpg'>This referenceNo has exists"
});
var dialogWidth;
var isLoaded = 0;
var orderJson = '';
var isCheckUpload = 0;
var shipMethods = [];
var countries = [];

$(function(){
	dialogWidth = $(document).width() - 50;
    validate();
    selfpickup();//按不同类型添加表单规则
    
	$("#batchAdd").dialog({		//批量上传控制
			autoOpen : false,
			width : 500,
			modal : true,
			show : "slide",
			buttons : {
				'submit' : function() {
					checkType();
					$(this).dialog('close');
				},
				'close' : function() {
					$(this).dialog('close');
				}
			}
	});
	
	$("#messageTip").dialog({
			autoOpen : false,
			width : 500,
			modal : true,
			show : "slide"
	});
	
	$('#orderInfo').dialog({
        bgiframe: true,
        autoOpen: false,
        width: dialogWidth,
        modal: true,
        overlay: { background:"#000",filter:"alpha(opacity=50)",opacity:0.5 },
        zIndex:1000,
        show:"slide"
    });

    $("[name=order_type]").click(function(){
        selfpickup();
    });
    
    $(".order_type").click(function(){
    	var order_type = $(this).val();
    	if(order_type==1){
    		$(".order_type_row").hide();
    	}else{
    		$(".order_type_row").show();    		
    	}    	
    });
    
});

function validate(){
    $("#editForm").validate({
   		rules:{
   			customer_order_code:{
   				remote:{
   					url:"/merchant/orders/validate-refno",
   					data:{
   						orderId:orderId
   					}
   				}
   			}
   		},
   		errorPlacement:function(error, element){
            element.parent().parent().children(".right").html(error);
   		},
   		success:function(label){
   			var length = label.parent().parent().children(".middle").children(".selectForm").length;
   			var name = "";
   			if(length > 0){
   				name =  label.parent().parent().children(".middle").children(".selectForm").attr("name");
   			}

   			if(name != "shipping_method"){
   				label.parent().parent().children(".right").children().append("<img src='/images/yes.gif'>");
   			}else{
   				getCost();
   			}
   		}
   	});
}

function checkProduct(){
	 if($(".product_sku").length==0){
		$(".productError").html("<img src='/images/error.jpg'>Product can not be empty!");
		$(".productError").show();
		return false;
	 }
	 $(".productError").html("");
	 $(".productError").hide();
	 return true;
}

function sumbitOrder(){
	if((!$("#editForm").valid() | !checkProduct())){
		return false;
	}
	if(($('[name =shipping_fee_estimate]').val() == "") && !getselfpickup()){
		return false;
	}
    var formData =$('#editForm').serialize();
	$.ajax({
		type: "POST",
		async: false,
		dataType: "json",
		url: "/merchant/orders/edit",
		data:formData,
		success: function(json) {
			var html ="";
            if(json.ask){
                var html ='<p class="alertMsg"><img src="/images/yes.gif">'+json.list.message+'</p>';
                $('#ProductList').html('');
                $('#cost').html('');
                $('.all_weight').html('');
                $('#flushMessage').html(html);
				$('#editForm').resetForm();
				$('.flushMessageDiv').dialog("open");
            }else{
            	
               if(json.list.message){
                    html += '<p class="alertMsg"><img src="/images/no.gif">'+json.list.message+'</p>';               
               }
            	if(json.list.error){
	            	 var error= json.list.error;	                
	                $.each(error,function(key,item){
	                    html += '<p class="alertMsg"><img src="/images/no.gif">'+item+'</p>';
	                });
            	}
                $('#message').html(html);
				 $('.messageDiv').dialog("open");
            }
           
		}
	});
}

function getShipping(){
    var warehouse_id =$('[name=warehouse_id]').val();
    var country_id =$('[name=consignee_country_id]').val();
    $('[name=shipping_method] > option').not(':first').remove();
	$.ajax({
		type: "POST",
		async: false,
		dataType: "json",
		url: "/merchant/orders/get-shipping",
		data:{
            'warehouse_id':warehouse_id,'country_id':country_id},
		success: function(json) {
			var html ="";
            if(json.ask){
                html = "";
                $.each(json.list,function(key,item){
                    html += "<option value='"+item.st_code+"'>"+item.st_code+"</option>";
					//html += "<option value='"+item.st_code+"'>"+item.st_code+"("+item.st_name_cn+")</option>";
                })
                $("[name=shipping_method]").append(html);
            }
		}
	});
    getCost();
}

function getCost(){
    $('#cost').html('');
    $('[name =shipping_fee_estimate]').val('');
    var weight =$('.all_weight').html();
    var warehouse_id =$('[name=warehouse_id]').val();
    var country_id =$('[name=consignee_country_id]').val();
    var shipping_method =$('[name=shipping_method]').val();
    if(country_id==''|| shipping_method=='' || weight==0){
        return false;
    }
    var product_sku = "";
    $(".product_sku").each(function(){
    	product_sku+=$(this).val()+",";    	
    });
	$.ajax({
		type: "POST",
		async: false,
		dataType: "json",
		url: "/merchant/orders/get-cost",
		data:{
            'warehouse_id':warehouse_id,
            'country_id':country_id,
            'shipping_method':shipping_method,
            'weight':weight,
            'product_sku':product_sku
        },
		success: function(json) {
			var html ="";
            if(json.ask){
                $('#cosInfo').html('The estimated cost will be <span class="red" id="cost">'+json.list.inter_fee+'</span>RMB.</span>');
                $('[name =shipping_fee_estimate]').val(json.list.inter_fee);
            }else{
				$('#cosInfo').html("<img src='/images/error.jpg'>No price");
				$('[name =shipping_fee_estimate]').val("");
			}
		}
	});

}

function checkAll(obj){
	if(jQuery (obj).attr("checked")=='checked'){
		jQuery ('.checkProduct').attr('checked',true);
	}else{
		jQuery ('.checkProduct').attr('checked',false);
	}
}

function getselfpickup(){
    if($("[name ='order_type']:checked").val()=='1'){
        return true;
    }else{
        return false;
    }
}

function selfpickup() {
    if (getselfpickup()) {
        $(".tab-div").find(".middle ").find(".red").html('');
        $(".tab-div").find(".right").html('');
        $("[name=customer_order_code]").parent().parent().find('.red').html("*");
        $("[name=customer_order_code]").rules("add", {required:true});
        $("[name=consignee_first_name]").rules("remove");
        $("[name=consignee_last_name]").rules("remove");
        $("[name=consignee_country_id]").rules("remove");
        $("[name=shipping_method]").rules("remove");
        $("[name=consignee_address1]").rules("remove");
    } else {
        $("[name=consignee_first_name]").parent().parent().find('.red').html("*");
        $("[name=consignee_last_name]").parent().parent().find('.red').html("*");
        $("[name=consignee_country_id]").parent().parent().find('.red').html("*");
        $("[name=shipping_method]").parent().parent().find('.red').html("*");
        $("[name=consignee_address1]").parent().parent().find('.red').html("*");
        $("[name=customer_order_code]").parent().parent().find('.red').html("");
        $("[name=consignee_first_name]").rules("add", { required:true});
        $("[name=consignee_last_name]").rules("add", { required:true});
        $("[name=consignee_country_id]").rules("add", {required:true});
        $("[name=shipping_method]").rules("add", {required:true});
        $("[name=consignee_address1]").rules("add", {required:true});
        $("[name=customer_order_code]").rules("remove", "required");
    }
}

function batchAddOrder(){
	$(".batchAddTips").html("");
	$('#batchAdd').dialog('open');
}

function  checkType(){	//检查上传文件格式
	orderFile = $('#orderFile').val();
	var uploadType = new Array(".csv", ".xls");	
	var ext = orderFile.slice(orderFile.lastIndexOf(".")).toLowerCase();
	for(i = 0; i < uploadType.length; i++){			
		if(ext && uploadType[i] == ext){ 
		    initUpload();
			return false;
		}
	}
	
	if('' == orderFile){
		msg='Please select upload file';	//请选择上传文件
	}else{
		msg='Upload file format must be XLS or CSV';	//上传文件格式必须是txt,csv,或xls
	}
	
    var errorMsg = '<p><img src="/images/error.jpg" />'+msg+'</p>';
	$("#messageTip").html(errorMsg).dialog("open"); 	
	return false;	
}

//初始化，判断是否需要从服务器加载数据
function initUpload(){
	if(isLoaded){
		$("#orderInfo").dialog("open");
		return false;
	}
	ajaxUpload();
}

function ajaxUpload(){
	$("#messageTip").dialog("open");
	$("#messageTipOutput").html("<center><img src='/images/ajaxLoader.gif'/></center>");
	var options = { 
		async:false,
		dataType: 'json',
		success: function(json) {			
			$("#messageTip").dialog("close");
			var html = '';
			if(!json.ask){
				$.each(json.error,function(key,val){
					html += '<span>'+val+'</span> <br />';
				});	
				$("#messageTip").dialog("open");			
				$("#messageTipOutput").html(html);
			}else {
				orderJson = json;
				loadList(json.data);			//加载列表
			}
			
		}
	};
	
	$('#uploadForm').ajaxSubmit(options);
	return true;
}

function loadList(data){
	var html = '';
	$.each(data,function(key,item){	//josn.data  对应 $orderArr	
		var colorSet = '';
		if(item.has_error){
			colorSet = 'color:red;';
		}
		html += '<tr style="'+colorSet+'">';
		html += '<td rowspan="2">&nbsp;';
		if(!item.has_error && isCheckUpload){
			html += '<input class="checked" type="checkbox" value="'+item.customer_order_code+'" name="ReferenceNo" />';
		}
		html += '</td>';					
		html += '<td rowspan="2" class="toggleCode" toggleId="'+item.customer_order_code+'" fname="customer_order_code">';
		html += '<span class="modifyText'+key+'">'+item.customer_order_code+'</span></td>';
		html += '<td fname="shipping_method"><span class="modifyList'+key+'" fvalue="'+item.shipping_method+'">'+item.shipping_method+'</span></td>';
		html += '<td fname="consignee_country_id"><span class="modifyList'+key+'" fvalue="'+item.consignee_country_id+'">'+item.country+'</span></td>';
		
		html += '<td fname="consignee_first_name"><span class="modifyText'+key+'">'+item.consignee_first_name+'</span></td>';
		html += '<td fname="consignee_last_name"><span class="modifyText'+key+'">'+item.consignee_last_name+'</span></td>';
		html += '<td fname="consignee_city"><span class="modifyText'+key+'">'+item.consignee_city+'</span></td>';
		html += '<td fname="consignee_region"><span class="modifyText'+key+'">'+item.consignee_region+'</span></td>';
		html += '<td fname="consignee_zip"><span class="modifyText'+key+'">'+item.consignee_zip+'</span></td>';
		
		html += '<td fname="email"><span class="modifyText'+key+'">'+item.email+'</span></td>';
		html += '<td fname="company"><span class="modifyText'+key+'">'+item.company+'</span></td>';
		html += '<td fname="consignee_phone"><span class="modifyText'+key+'">'+item.consignee_phone+'</span></td>';
		html += '<td rowspan="2"><img src="/images/icon_edit.gif" id="modifyIcon'+key+'" onclick="triggerEdit('+key+')" /></td>';
		html += '</tr>';
					
			html += '<tr style="'+colorSet+'">';
			html += '<td class="addrTd" colspan="5"><div class="addrDiv">Address1:</div>';
			html += '<div class="address" fname="consignee_address1"><span class="modifyText'+key+'">'+item.consignee_address1+'</span></div></td>';						
			html += '<td class="addrTd" colspan="5"><div class="addrDiv">Address2:</div>';
			html += '<div class="address" fname="consignee_address2"><span class="modifyText'+key+'">'+item.consignee_address2+'</span></div></td>';						
			html += '</tr>';
					
		// 产品列表
			html += '<tr id="detailInfo'+item.customer_order_code+'" class="detailInfo" style="display:none;font-style:italic;">';
			html += '<td colspan="8">';
			html += '<table  width="100%" style="background:#E2F1F9;" id="productTable'+key+'">';
				html += '<tr><td colspan="6"><span class="button-2" onclick="OpenProductDiv2('+key+')">Add Products</span></td></tr>';
				//产品列表标题
				html += '<tr style="font-weight:bold;">';
				html += '<td>SKU</td><td>SKUName</td><td>Category</td>';
				html += '<td>OrderQty</td><td>Weight(Kg)</td><td>Action</td>';
				html += '</tr>';

				$.each(item.order_product,function(key2,item2){
					html += '<tr class="product'+item2.product_id+'Line'+key+'">';
					html += '<td>'+item2.product_title+'</td>';	//SKU 产品名称
					html += '<td><input type="hidden" class="inputText product_sku2" name="product_sku2[]" value="'+item2.product_sku+'" readonly/>'+item2.product_sku+'</td>';	//SKUname 产品CODE
					html += '<td>'+item2.category+'</td>';
					
					html += '<td fname="op_quantity" fkey="'+key+'" fsku="'+item2.product_sku+'">';
					html += '<input type="text" class="inputText" name="submitQuantity[]" value="'+item2.op_quantity+'" onblur="quantitySave(this)" style="width:80px;text-align:right" />';
					html += '</td>';
					html += '<td>'+item2.op_weight+'</td>';
					html += '<td><img src="/images/icon_del.gif" fkey='+key+' fvalue='+item2.product_sku+' onclick="delProduct(this)" class="cursor" title="Delete"/></td>';
					html += '</tr>';
				});
					
			html += '</table></td>';
			html += '<td colspan="5">&nbsp;</td>';
			html += '</tr>';
					
		// 错误提示
		if(!item.error_arr){
			
		}else{
			html += '<tr>';
			html += '<td colspan="14" style="background:#FFFFCE;border-bottom: 2px solid #AECED9;">&nbsp;';
			$.each(item.error_arr,function(key3,item3){
				html += item3+';&nbsp;';						
			});
			html += '</td><tr>';
		}
		
	});							
	$("#orderInfoList").html(html);		
			
	$('.toggleButton').click(function(){
		if($(this).attr("status") != 1){
			$(".detailInfo").hide();
			$(this).attr("status",1);
			$(this).html("Unfold");
		}else{
			$(".detailInfo").show();
			$(this).attr("status",0);
			$(this).html("Fold");
		}
	});	
	$(".toggleCode").click(function(){
		$("#detailInfo"+$(this).attr("toggleId")).toggle();
	});
	
	isLoaded = 1;
	$("#orderInfo").dialog("open");
	
}


// 触发批量上传时 订单信息编辑
function triggerEdit(key){
	loading();	
	$('.modifyText'+key).each(function(i){
		var $parentObj = $(this).parent();
		var width = $parentObj.width()-10;
		var text = $.trim($(this).text());		
		
		var fname = $(this).parent().attr('fname');
		var html = '';
		html += '<input type="text" name="'+fname+'" value="'+text+'" class="modifyInput'+key+'" />';	
		$parentObj.html(html);
		$parentObj.children('input').width(width);
	});

	$('.modifyList'+key).each(function(i){
		var $parentObj = $(this).parent();
		var width = $parentObj.width()-10;
		var text = $.trim($(this).text());
		var fname = $(this).parent().attr('fname');
		var fvalue = $(this).attr('fvalue');
		
		var html = '';
		if(fname == 'shipping_method'){
			if(shipMethods.length==0) getShipMethod();
			html += '<select name="'+fname+'" class="modifySelect'+key+'">';			
			$.each(shipMethods,function(key,item){
				if(fvalue == item){
					html += '<option value="'+item+'" selected>'+item+'</option>';
				}else{
					html += '<option value="'+item+'">'+item+'</option>';	
				}							
			});
			html += '</select>';
			
		}else if(fname == 'consignee_country_id'){
			if(countries.length==0) getCountries();
			html += '<select name="'+fname+'" class="modifySelect'+key+'">';
			$.each(countries,function(key,item){
				if(fvalue == item.country_id){
					html += '<option value="'+item.country_id+'" selected>'+item.country_code+' '+item.en_name+'</option>';
				}else{
					html += '<option value="'+item.country_id+'">'+item.country_code+' '+item.en_name+'</option>';	
				}
			});
			html += '</select>';
		}
		$parentObj.html(html);
		$parentObj.children('select').width(width);
	});
	
	var saveHtml = '<img src="/images/save_icon.jpg" id="saveIcon'+key+'" onclick="triggerSave('+key+')" />';
	$('#modifyIcon'+key).parent().html(saveHtml);
	closeLoading();
}

// 触发批量上传时 订单信息保存
function triggerSave(key){
	loading();
	$('.modifyInput'+key).each(function(i){
		var text = $.trim($(this).val());
		var fname = $(this).parent().attr('fname');		
		orderJson.data[key][fname] = text;		
		var html = '';
		html += '<span class="modifyText'+key+'">'+text+'</span>';	
		$(this).parent().html(html);
	});
	
	$('.modifySelect'+key).each(function(i){
		var text = $(this).find('option:selected').text();
		var fvalue = $(this).val(); 
		var fname = $(this).parent().attr('fname');
		orderJson.data[key][fname] = fvalue;
		
		var html = '';
		html += '<span class="modifyList'+key+'" fvalue="'+fvalue+'">'+text+'</span>';	
		$(this).parent().html(html);		
	});
	
	var editHtml = '<img src="/images/icon_edit.gif" id="modifyIcon'+key+'" onclick="triggerEdit('+key+')" />';
	$('#saveIcon'+key).parent().html(editHtml);
	closeLoading();
}


// 获取物流方式
function getShipMethod(){
	$.ajax({
		type: "POST",
		async: false,
		dataType: "json",
		url: "/merchant/orders/get-ship-method",		
		success: function(json) {
			if(!json.ask){
				shipMethods = [];
			}else{
				shipMethods = json.data;
			}
		}
	});
}

// 获取 国家信息
function getCountries(){
	$.ajax({
		type: "POST",
		async: false,
		dataType: "json",
		url: "/merchant/orders/get-countries",		
		success: function(json) {
			if(!json.ask){
				countries = [];
			}else{
				countries = json.data;
			}
		}
	});
}

//批量检查数据
function uploadCheckData(){	
	$("#messageTip").dialog("open");
	$("#messageTipOutput").html("<center><img src='/images/ajaxLoader.gif'/></center>");
	$.ajax({
		type: "POST",
		async: false,
		dataType: "json",
		url: "/merchant/orders/upload-check-data",
		data:{'orderJson':orderJson},
		success: function(json) {
			$("#messageTip").dialog("close");
			if(!json.ask){
				alert('Data Err');
			}else {
				$('#batchAddBtn').show();
				isCheckUpload = 1;	//已检查
				orderJson = json;
				loadList(json.data);
			}
		}
	});
}

// 批量提交，写入数据表
function batchSubmit(){
	var ReferenceNoArr=[];
	$('input:checkbox[name="ReferenceNo"][checked]').each(function(i){
		ReferenceNoArr[i]=$(this).val();		
    });
    
    if(ReferenceNoArr.length==0){
    	$('#tipDialog2').html("You must select at least one line").dialog("open");
		return;
    }

    $.each(orderJson.data,function(key,val){
    	if($.inArray(val['customer_order_code'],ReferenceNoArr) == -1 ){
    		orderJson.data[key] = [];
    	}    	
    });

    loading();
    $.ajax({
        type: "POST",
        async: false,
        dataType: "json",
        url: "/merchant/orders/excel-upload-add",
        data:{'orderJson':orderJson},
        success: function(json) { 
        	var html ='';
        	$.each(json,function(key,res){
        		if(res.ask){
        			html +='<p class="alertMsg"><img src="/images/yes.gif">'+res.list.message+'</p>';         	
         		}else{ 
         			if(res.list.message){
                    	html += '<p class="alertMsg"><img src="/images/no.gif">'+res.list.message+'</p>';               
               		}
            		if(res.list.error){
	            	 	var error= res.list.error;	                
	               	 	$.each(error,function(key,item){
	                    	html += '<p class="alertMsg"><img src="/images/no.gif">'+item+'</p>';
	                	});
            		}
         			
         		}
        		
        	});        	
        	closeLoading();
         	$("#tipDialog").html(html).dialog("open");         	
      	}
      	
    });
    
}
